package com.stedu.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.stedu.bean.Admin;
import com.stedu.bean.RespBean;
import com.stedu.exception.SteduException;
import com.stedu.service.impl.AdminServiceImpl;
import com.stedu.utils.JwtUtils;
import com.stedu.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;

@CrossOrigin
@Controller
public class AdminLoginController{
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AdminServiceImpl adminService;
    //登录

    @ResponseBody
    @PostMapping("/login")
    public RespBean login(@Validated String username, String password, String user, String captchaId, String captcha) throws SteduException {
        //判断验证码--Redis中保存的验证码文本对比
        String captchaRedis =(String)redisUtil.get(captchaId);
        if(captchaRedis==null||(captchaRedis != null&& !captchaRedis.equalsIgnoreCase(captcha))){
            return RespBean.error("验证码错误请刷新后重新输入");
        }

        Admin admin= adminService.login(username, password,user);
            //登录之后产生jwt发给前端外加权限
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        String jwt = JwtUtils.generateJwt(map);

        return  RespBean.ok("登录成功",jwt);
    }

    @ResponseBody
    @GetMapping("/captcha")
    protected RespBean captcha() throws IOException {
        //生成验证码对象
        LineCaptcha captcha = new LineCaptcha(120, 38, 4, 20);
        //获取验证文本
        String code = captcha.getCode();
        //唯一的ID（key）雪花生成
        String captchaId= IdUtil.getSnowflakeNextIdStr();
        redisUtil.set(captchaId, code,60);
        //将captchaId和验证码转为图片 --字符串
        String captchaImageBase64Data = captcha.getImageBase64Data();

        HashMap<String, Object> map = new HashMap<>();
        map.put("captchaId",captchaId);
        map.put("captchaImageBase64Data", captchaImageBase64Data);

        return  RespBean.ok("",map);

    }
    @ResponseBody
    @PostMapping("login/insert")
    public RespBean insert(@RequestBody Admin admin) throws SteduException {

        if (adminService.insert(admin)) {
            return RespBean.ok("注册成功~~~");
        } else {
            return RespBean.error("注册失败，请重新注册");
        }

    }








}
